import indextou from "../modules/indextou.js"
import {$,$$} from "../modules/public.js"
import ajax from "../modules/ajax.js"
import updata from "../modules/updata.js"

indextou()
$(".Cart").innerHTML=`购物车(${JSON.parse(sessionStorage.getItem("data"))?.length||0})`
$(".exit").addEventListener("click", ()=>{
  location.assign("http://localhost:3000/index.html")
})
const data=JSON.parse(sessionStorage.getItem("data"))

if(data.length){
  let str=''
  data.forEach((val,index) => {
  str+=`
  <div id="${val.proID}" class="products" name="${index}">
  <input type="checkbox" class="select">
  <img src="${val.img}">
  <span class="span1">${val.brief1}</span>
  <span class="price">${val.price}</span>
  <span class="num"><i>+</i><input type="text" value="${val.num}"><i>-</i></span>
  <span class="sum">${val.price*val.num}</span>
  <div class="btn">删除</div>
  </div>`
});
$(".cart-box").innerHTML=str
  $$(".num i")[0].onclick=function(){
    $(".num input").value=$(".num input").value*1+1
    const proID=this.parentNode.parentNode.id
    updata(proID,data)
  }
  $$(".num i")[1].onclick=function(){
    const proID=this.parentNode.parentNode.id
    if($(".num input").value<=1){
      $(".num input").value=1
      updata(proID,data)
    }else{
      $(".num input").value=$(".num input").value-1
      updata(proID,data)
    }
  }
  $(".products .btn").onclick=function(){
    const proID=this.parentNode.id
    ajax({
      url:"http://localhost:3000/cartdel",
      method:"post",
      data:{proID}
    }).then(res=>{
      console.log(res);
      sessionStorage.setItem("data",res)
      location.assign("")
    })
  }
  $(".allSelect").onclick=function(){
    $$(".select").forEach(val=>{
      val.checked=$(".allSelect").checked
    })
  }
  for(let i=0;i<$$(".select").length;i++){
    $$(".select")[i].onclick=function(){
      const state= [...$$(".select")].every(val=>{
        return val.checked===true
      }) 
      $(".allSelect").checked=state
    }
  }
}